import os
import random
import signal
import sys
from numpy.typing import NDArray
import numpy as np

from utils import convert_point, crd_grid_to_game, one_zero_map,point_to_line_vector

# TOP上移、DOWN 下移、LEFT 左移、RIGHT 右移、STOP 原地不动
MOVE={
  (0,0):'STOP',
  (0, 1):'RIGHT',
  (0, -1):'LEFT',
  (1, 0):'DOWN',
  (-1, 0):'TOP'
}
# map 一张0，1表示的能否通行的地图 ；0 表示不能通行
def calcDir(map,start,routes,speed,players):
  if len(routes)<2:
    print("error:route 不合法")
    return 'STOP'
  r0=np.array(routes[0])
  r1=np.array(routes[1])
  vector=r1-r0

  # 如果踩在泥巴地上尝试先回到平地
  vector_90=np.array([vector[1], -vector[0]])
  vx,vy=crd_grid_to_game(routes[0], 50)
  x_diff,y_diff=(vx-start[0])*abs(vector_90[0]),(vy-start[1])*abs(vector_90[1])
  diff=abs(x_diff+y_diff)
  if speed==5 and map[r0[0]][r0[1]]=='G' and diff>0:
    print(start,routes,speed)
    print('尝试回平地')
    v=np.array([x_diff, y_diff])
    v=v/np.linalg.norm(v)
    v=(v[0],v[1])
    return MOVE[v]
    
  pass_map=one_zero_map(map)
  if can_move(pass_map,start,vector,speed,players):
    return MOVE[(vector[0],vector[1])]
  
  r1=crd_grid_to_game(routes[0],50)
  r2=crd_grid_to_game(routes[1],50)
  
  # 三点共线，被其他玩家挡住去路
  if start[0]==r1[0]==r2[0] or start[1]==r1[1]==r2[1]:
      print(routes,start)
      return 'STOP'
  # 尝试先回到首节点
  vector=point_to_line_vector(start,r1,r2)
  return MOVE[(vector[0],vector[1])]
  
def can_move(map,points, dir, speed, players):
    # 每个格子的大小
    grid_size = 50
    
    # 当前方块的左上角坐标
    x, y =convert_point(points) 
    
    # 计算移动后的新左上角坐标
    new_x = x + dir[0] * 1
    new_y = y + dir[1] * 1
    
    # 将坐标转换为网格索引
    def get_grid_pos(px, py):
        grid_x = int(px // grid_size)
        grid_y = int(py // grid_size)
        return grid_x, grid_y
    
    # 获取方块的4个角坐标：左上、右上、左下、右下
    def get_block_corners(px, py):
        top_left = (px, py)
        top_right = (px + grid_size - 1, py)
        bottom_left = (px, py + grid_size - 1)
        bottom_right = (px + grid_size - 1, py + grid_size - 1)
        return [top_left, top_right, bottom_left, bottom_right]
    
    # 获取移动后方块4个角的网格坐标
    new_corners = get_block_corners(new_x, new_y)
    new_grid_positions = [get_grid_pos(corner[0], corner[1]) for corner in new_corners]
    
    # 检查所有角的网格坐标是否都在地图内并且可通行
    for gx, gy in new_grid_positions:
        # 检查是否超出地图边界
        if gx < 0 or gx >= len(map) or gy < 0 or gy >= len(map[0]):
            return False
        # 检查是否可通行
        if map[gx][gy] == 0:
            return False
   
    # 检查是否与其他玩家的方块重叠
    def blocks_overlap(p1, p2):
        """判断两个方块是否重叠，p1 和 p2 是左上角坐标"""
        p1_x, p1_y = p1
        p2_x, p2_y = p2
        return not (p1_x + grid_size <= p2_x or  # p1 在 p2 的左边
                    p1_x >= p2_x + grid_size or  # p1 在 p2 的右边
                    p1_y + grid_size <= p2_y or  # p1 在 p2 的上边
                    p1_y >= p2_y + grid_size)    # p1 在 p2 的下边
    
    # 检查新位置是否和其他玩家重叠
    new_x = x + dir[0] * speed
    new_y = y + dir[1] * speed
    for player in players:
        if blocks_overlap((new_x, new_y),convert_point(player)):
            return False
    
    return True

  
  
  
